from rest_framework import serializers
from .models import File

class FileSerializer(serializers.ModelSerializer):
    class Meta:
        model = File
        fields = ('id', 'name', 'file', 'uploaded_by', 'uploaded_at', 'size')
        read_only_fields = ('uploaded_by', 'uploaded_at', 'size')

    # 修正缩进：与 Meta 同级
    def validate_file(self, value):
        # 限制文件大小（5MB）
        if value.size > 5 * 1024 * 1024:
            raise serializers.ValidationError("文件大小不能超过5MB")
        # 限制文件类型
        if not value.name.lower().endswith(('.jpg', '.jpeg', '.png','.txt','xlsx')):  # 增加小写转换，避免大小写问题
            raise serializers.ValidationError("仅支持jpg、jpeg、png格式")
        return value